package org.smoozik.services.sequence;

import java.util.ArrayList;
import java.util.Collections;

import org.smoozik.services.musictheory.Partition;
import org.smoozik.services.musictheory.Token;

public class Sequence {

	// Duration in millisec, used to set the duration of a time
	private ArrayList<Token> tokens;

	public Sequence(int timeWeight) {
		tokens = new ArrayList<>();
	}

	public Sequence() {
		this(1000);
	}

	public void setPartition(Partition p) {
		for (Token token : tokens) {
			token.getFigure().setPartition(p);
		}
	}

	public void setChannel(int channel) {
		for (Token token : tokens) {
			token.setChannel(channel);
		}
	}

	public ArrayList<Token> getTokens() {
		return tokens;
	}

	public void setTokens(ArrayList<Token> tokens) {
		this.tokens = tokens;
	}

	public void addTokens(ArrayList<Token> tokens) {
		if (tokens == null) {
			tokens = new ArrayList<>();
		}
		this.tokens.addAll(tokens);
	}

	public void add(Token t) {
		if (tokens == null) {
			tokens = new ArrayList<>();
		}
		this.tokens.add(t);
	}

	public void setRythmicPattern(RythmicPattern pattern, int start) {
		Token tokenPattern = null;
		Token tokenSequence = null;
		double place = 0;
		if (start != 0) {
			place = tokens.get(start - 1).getPlace()
					+ tokens.get(start - 1).getDuration();
		}

		for (int i = 0; i < pattern.size(); i++) {
			tokenPattern = pattern.get(i);
			tokenSequence = tokens.get(i + start);

			tokenSequence.setPlace(place + tokenPattern.getPlace());
			tokenSequence.setDuration(tokenPattern.getDuration());
		}
	}

	public void setHarmonicPattern(HarmonicPattern pattern, int start) {
		Token tokenPattern = null;
		Token tokenSequence = null;

		for (int i = 0; i < pattern.size(); i++) {
			tokenPattern = pattern.get(i);
			tokenSequence = tokens.get(i + start);

			tokenSequence.setFigure(tokenPattern.getFigure());
		}
	}

	// public void repeat() {
	// ArrayList<Token> newTokens = new ArrayList<>(tokens.size() * 2);
	//
	// newTokens.addAll(tokens);
	//
	// for (Token t : this.tokens) {
	// newTokens.add(new Token(t.getFigure(), t.getDuration(), t
	// .getPlace() + 8 * getTimeWeight()));
	// }
	//
	// this.tokens = newTokens;
	// }

	public void sort() {
		Collections.sort(tokens);
	}

	public String serialize() {
		String s = "";
		s += "	<sequence>\n";

		for (Token t : this.tokens) {
			s += t.serialize();
		}

		s += "	</sequence>\n";

		return s;
	}

	public String toString() {
		String s = "";

		for (Token t : tokens) {
			s += t.toString() + "\n";
		}

		return s;
	}
}
